from flask import request, jsonify, Blueprint
from werkzeug.exceptions import BadRequest
from app import db
from app.likes.models import Like
from app.likes.schemas import like_schema, likes_schema
from app.recipes.models import Recipe
from app.auth.models import User

# 创建点赞模块的蓝图
likes_bp = Blueprint('likes', __name__)

@likes_bp.route('/', methods=['GET'])
def get_likes():
    """
    获取所有点赞列表
    ---
    响应：点赞列表
    """
    likes = Like.query.all()
    return jsonify(likes_schema.dump(likes))

@likes_bp.route('/<int:like_id>', methods=['GET'])
def get_like(like_id):
    """
    获取单个点赞的详细信息
    ---
    参数：like_id - 点赞ID
    响应：点赞详细信息
    """
    like = Like.query.get_or_404(like_id)
    return jsonify(like_schema.dump(like))

@likes_bp.route('/', methods=['POST'])
def create_like():
    """
    创建新点赞（点赞功能）
    ---
    请求体：点赞信息（用户ID和食谱ID）
    响应：创建成功的点赞信息
    """
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    # 验证必填字段
    required_fields = ['user_id', 'recipe_id']
    for field in required_fields:
        if field not in data:
            raise BadRequest(f'Missing required field: {field}')
    
    # 检查食谱是否存在
    recipe = Recipe.query.get(data['recipe_id'])
    if not recipe:
        raise BadRequest(f'Recipe not found: {data["recipe_id"]}')
    
    # 检查是否已经点赞
    existing_like = Like.query.filter_by(
        user_id=data['user_id'], 
        recipe_id=data['recipe_id']
    ).first()
    
    if existing_like:
        raise BadRequest('Recipe already liked by this user')
    
    # 创建点赞对象
    like = Like(
        user_id=data['user_id'],
        recipe_id=data['recipe_id']
    )
    
    db.session.add(like)
    db.session.commit()
    
    return jsonify(like_schema.dump(like)), 201

@likes_bp.route('/<int:like_id>', methods=['DELETE'])
def delete_like(like_id):
    """
    删除点赞（取消点赞功能）
    ---
    参数：like_id - 点赞ID
    响应：成功删除的消息
    """
    like = Like.query.get_or_404(like_id)
    
    db.session.delete(like)
    db.session.commit()
    
    return jsonify({'message': 'Like deleted successfully'})

@likes_bp.route('/user/<int:user_id>', methods=['GET'])
def get_likes_by_user(user_id):
    """
    获取指定用户的所有点赞
    ---
    参数：user_id - 用户ID
    响应：点赞列表（包含食谱信息）
    """
    likes = Like.query.filter_by(user_id=user_id).order_by(Like.created_at.desc()).all()
    return jsonify(likes_schema.dump(likes))

@likes_bp.route('/check', methods=['GET'])
def check_like():
    """
    检查用户是否已点赞指定食谱
    ---
    参数：user_id - 用户ID, recipe_id - 食谱ID
    响应：是否已点赞（布尔值）
    """
    user_id = request.args.get('user_id', type=int)
    recipe_id = request.args.get('recipe_id', type=int)
    
    if not user_id or not recipe_id:
        raise BadRequest('Missing required parameters: user_id and recipe_id')
    
    like = Like.query.filter_by(user_id=user_id, recipe_id=recipe_id).first()
    
    return jsonify({
        'is_liked': like is not None,
        'like_id': like.id if like else None
    })

@likes_bp.route('/count/<int:recipe_id>', methods=['GET'])
def get_like_count(recipe_id):
    """
    获取指定食谱的点赞数量
    ---
    参数：recipe_id - 食谱ID
    响应：点赞数量
    """
    # 检查食谱是否存在
    recipe = Recipe.query.get(recipe_id)
    if not recipe:
        raise BadRequest(f'Recipe not found: {recipe_id}')
    
    count = Like.query.filter_by(recipe_id=recipe_id).count()
    
    return jsonify({
        'recipe_id': recipe_id,
        'like_count': count
    })

@likes_bp.route('/user/<int:user_id>/count', methods=['GET'])
def get_like_count_by_user(user_id):
    """
    获取指定用户的点赞总数
    ---
    参数：user_id - 用户ID
    响应：点赞总数
    """
    # 检查用户是否存在
    user = User.query.get(user_id)
    if not user:
        raise BadRequest(f'User not found: {user_id}')
    
    count = Like.query.filter_by(user_id=user_id).count()
    
    return jsonify({
        'user_id': user_id,
        'count': count
    })